/**
 项目JS主入口
 **/
layui.define(['layer','form','table'], function (exports) {
    var  layer = layui.layer
		,form = layui.form
		,table = layui.table
		, $ = layui.$;
    
	form.on('submit(demo)', function(data){
		var tab = new Object; 
		tab.status ="str";
		tab.data = data.field.content;;
		socket.send(JSON.stringify(tab));
		$('#content').val("");
		return false;
	});
  
	//回车按键事件
	$('#content').on('keydown', function(e){
		if(e.keyCode == 13){
			$('#qf_but').click();
		}
	});
	
	//回车按键事件
	$('#content1').on('keydown', function(e){
		if(e.keyCode == 13){
			$('#send_but').click();
		}
	});
	
	app = {};
	
	var hspost;   //单独端口
	var socket;
	if(typeof(WebSocket) == "undefined") {
		layer.msg("您的浏览器不支持WebSocket");
		
	}
	
	//信息来后状态
	var init_msg = function(data){
		switch(data.status)
			{
			case "init":
				$("#msgtop").html(data.h_top);
				$(".rcont").html(data.h_right);
				table.init('demo', {limit: 10 });
				$(".footer > span").text("已连接到服务器");
				break;
			case "str":
				$("#msgtop").append(data.data);
				break;
			case "lose":
				$(".rcont").html(data.h_right);
				table.init('demo', {limit: 10 });
				break;
			case "onesend":
				app.open_windows(data.name,data.hp)
				$("#si_msgtop").append(data.data);
			break;
			default:
			  
			}
	}
	
	app.socksatr = function(){
		//实现化WebSocket对象，指定要连接的服务器地址与端口
		socket = new WebSocket("ws://127.0.0.1:8876/aardio");
		//打开事件
		socket.onopen = function() {
			var tab = new Object; 
		    tab.status ="init";
			tab.name="服务端";
			var str = JSON.stringify(tab);
			socket.send(str);
			app.status ="1";
			$(".footer").append("  <span>本地监听已打开</span>");
		};
		//获得消息事件
		socket.onmessage = function(msg) {
			var data = msg.data;
			data = $.parseJSON(data);
			init_msg(data);
			//保证滚动条到最底部
			var div = document.getElementById('msgtop');
			div.scrollTop = div.scrollHeight;
		};
		//关闭事件
		socket.onclose = function() {
			layer.msg("Socket已关闭");
		};
		//发生了错误事件
		socket.onerror = function() {
			layer.msg("发生了错误");
		}
		
		
		
		//关闭
		$("#btnClose").click(function() {
			socket.close();
		});

	}
	setTimeout('app.socksatr()','8000');   //延迟5秒运行本地sock

		//监听窗口大小改变事件
	$(window).resize(function() {
	   table.init('demo', {limit: 10 });
	})

	
	//弹窗
	app.open_windows = function(name,hs){
		hspost = hs;
		layer.open({
		  title:"和"+name+"单独聊天中",
		  id:"mycen",
		  type: 1,
		  area: ['90%', '80%'],
		  content: $("#singsed")
		});
	}
	
	
	form.on('submit(sing)', function(data){
		var tab = new Object; 
		tab.status ="onesend";   //单独聊天状态
		tab.data = data.field.content1;
		tab.hp = hspost;
		socket.send(JSON.stringify(tab));
		$('#content1').val("");
		return false;
	});
	

    exports('app', {});
});